package com.wdb.modules.mnt.rest;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wdb.annotation.Log;
import com.wdb.exception.BadRequestException;
import com.wdb.modules.mnt.domain.Database;
import com.wdb.modules.mnt.domain.vo.DatabaseQueryCriteria;
import com.wdb.modules.mnt.service.DatabaseService;
import com.wdb.modules.mnt.util.SqlUtils;
import com.wdb.utils.PageResult;
import com.wdb.utils.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/9/4 星期三 10:24
 */
@Slf4j
@Api(tags = "运维：数据库管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/database")
public class DatabaseController {
  private final DatabaseService databaseService;
  private final String fileSavePath = FileUtil.getTmpDirPath() + "/";

  @ApiOperation(value = "测试数据库链接")
  @PostMapping("/testConnect")
  public ResponseEntity<Object> testConnect(@Validated @RequestBody Database resources) {
    return new ResponseEntity<>(databaseService.testConnect(resources), HttpStatus.CREATED);
  }

  @ApiOperation("新增数据库连接")
  @PostMapping
  public ResponseEntity<Object> createDatabase(@Validated @RequestBody Database resources) {
    databaseService.create(resources);
    return new ResponseEntity<>(HttpStatus.CREATED);
  }

  @ApiOperation("查询database")
  @Log("查询")
  @GetMapping
  public ResponseEntity<PageResult<Database>> queryDatabase(
      DatabaseQueryCriteria criteria, Page page) {

    return new ResponseEntity<>(databaseService.queryAll(criteria, page), HttpStatus.OK);
  }

  @ApiOperation(value = "执行SQL脚本")
  @PostMapping(value = "/upload")
  public ResponseEntity<Object> uploadDatabase(
      @RequestBody MultipartFile file, HttpServletRequest request) throws Exception {
    String id = request.getParameter("id");
    Database database = databaseService.findById(id);
    String filename;
    if (database != null) {
      filename = file.getOriginalFilename();
      log.info("path---{}", fileSavePath + filename);
      File excuteFile = new File(fileSavePath + filename);
      FileUtil.del(excuteFile);
      file.transferTo(excuteFile);
      String result =
          SqlUtils.executeFile(
              database.getJdbcUrl(), database.getUserName(), database.getPwd(), excuteFile);
      return new ResponseEntity<>(result, HttpStatus.OK);
    } else {
      throw new BadRequestException("Database not exist");
    }
  }
}
